#include "SkillSelectScreen.h"
#include "SimpleAudioEngine.h"
#include "Skills/SkillsLoader.h"
#include "Supporting/Enums/EnumScreenType.h"
#include "Supporting/Enums/EnumTutorialType.h"
#include "Supporting/TutorialLoader.h"
#include "Supporting/PlayerData.h"
#include "../FlowController.h"

using namespace cocos2d;
using namespace CocosDenshion;

//===== CONSTRUCTOR =====
SkillSelectScreen::SkillSelectScreen() : BaseScreen()
{
	_screenID = SCREEN_SKILLSELECT;
	_currentPanel = 0;
	_currentSelectedSlot = 0;

	_skillList = mySkillsLoader->getSkillsList();

	_bgFileName = CCString::create("Menu/Skills/[BG] Skill Select.png");

	_slots[0] = PlayerData::getSkillNumber(1);
	_slots[1] = PlayerData::getSkillNumber(2);
	_slots[2] = PlayerData::getSkillNumber(3);
}
//===== DESTRUCTOR =======
SkillSelectScreen::~SkillSelectScreen()
{
	_skillList->release();
	_skillList = NULL;

	if (mySkillsLoader != 0)
		delete mySkillsLoader;
}

/*
 * @function: createLayer
 * @brief: Create SkillSelectScreen layer
 * @return: SkillSelectScreen layer
 */
BaseScreen* SkillSelectScreen::createLayer()
{
    // 'layer' is an autorelease object
	SkillSelectScreen *layer = SkillSelectScreen::create();

	layer->setSkillsLoaderReference(new SkillsLoader());

    // return the scene
    return layer;
}

/*
 * @function: loadScreen
 * @brief: Load the screen for skill select screen
 * @param flowcontroller: reference to FlowController
 * @param bgfilename: filename to the background image
 * @result: create the skill select screen
 */
void SkillSelectScreen::loadScreen(FlowController *flowcontroller)
{
	BaseScreen::loadScreen(flowcontroller);

	CCSize _screenSize = CCDirector::sharedDirector()->getWinSize();
	//==========================BACKGROUND============================
	CCSprite *bgTitle = CCSprite::create("Menu/Skills/[Text] Skill Select.png");
	bgTitle->setScale(_scaleFactor);
	bgTitle->setPosition(ccp(_screenSize.width/2,_screenSize.height-(60*_scaleFactor)));
	this->addChild(bgTitle);

	//==========================PANELS============================
	for( int i = 0 ; i < MAXSKILLS ; i++ )
	{
		CCSprite *skillPanelList = CCSprite::create("Menu/Skills/[UI] Skill Select - Panel.png");
		skillPanelList->setScale(_scaleFactor);
		skillPanelList->setPosition(ccp(_screenSize.width/2,_screenSize.height/2));

		CCString *title = CCString::createWithFormat("Menu/Skills/[UI] Skill List - %s.png",((BaseSkill*)_skillList->objectAtIndex(i))->returnSkillName()->getCString());
		CCSprite *skillTitle = CCSprite::create(title->getCString());
		//skillTitle->setScale(_scaleFactor);
		skillTitle->setPosition(ccp(230,380));
		skillPanelList->setTag(SKILLPANEL+i);
		skillPanelList->addChild(skillTitle);

		CCString *image = CCString::createWithFormat("Menu/Skills/[Skill] %s Mid.png",((BaseSkill*)_skillList->objectAtIndex(i))->returnSkillName()->getCString());
		CCSprite *skillImage = CCSprite::create(image->getCString());
		skillImage->setScale(0.9);
		//skillImage->setScale(_scaleFactor-(0.2*_scaleFactor));
		skillImage->setPosition(ccp(230,260));
		skillImage->setTag(SKILLPANELSKILLIMAGE+i);
		skillPanelList->addChild(skillImage);

		CCString* description = ((BaseSkill*)_skillList->objectAtIndex(i))->returnSkillDescription();
		CCLabelTTF * font = CCLabelTTF::create(description->getCString(), "Font/CarterOne.ttf", 22);
		font->setHorizontalAlignment(kCCTextAlignmentLeft);
		font->enableStroke(ccc3(0,0,0),2,true);
		font->setPosition(ccp(225,115));
		skillPanelList->addChild(font);

		this->addChild(skillPanelList);

		if( i > 0 )
			skillPanelList->setPositionX((i+1)*_screenSize.width/2);
	}

	//=========================SKILL BAR============================
	CCSprite *skillSelectBar = CCSprite::create("Menu/Skills/[UI] Skill Select - Equips Bar.png");
	skillSelectBar->setScale(_scaleFactor);
	skillSelectBar->setPosition(ccp(_screenSize.width/2,_screenSize.height/2 - (250*_scaleFactor)));
	this->addChild(skillSelectBar);

	for( int i = 0 ; i < 3 ; i++ )
	{
		CCSprite *skillSelectBase;
		if( i != 0 )
			skillSelectBase = CCSprite::create("Menu/Skills/[Skill Button] Base.png");
		else
			skillSelectBase = CCSprite::create("Menu/Skills/[Skill Button] Base Selected.png");
		skillSelectBase->setScale(_scaleFactor);
		skillSelectBase->setPosition(ccp(_screenSize.width/2 + ((i*120-90)*_scaleFactor),_screenSize.height/2 - (250*_scaleFactor)));
		skillSelectBase->setTag(SKILLSLOT+i);

		this->addChild(skillSelectBase);

		//If not -1, means there is an existing image
		//Load the skill image and add on top
		if( _slots[i] != -1 )
		{
			//Get base location
			CCSprite *imagetoreplace = (CCSprite*)((this->getChildByTag((SKILLPANEL+_slots[i])))->getChildByTag(SKILLPANELSKILLIMAGE+_slots[i]));

			CCSprite *insertimage = CCSprite::createWithTexture(imagetoreplace->getTexture());
			insertimage->setTag(SKILLSLOTIMAGE+i);
			insertimage->setPosition(skillSelectBase->getPosition()+ccp(2*_scaleFactor,-1*_scaleFactor));
			insertimage->setScale(_scaleFactor-(0.6*_scaleFactor));

			this->addChild(insertimage);
		}
	}

	//================LEFT RIGHT BUTTONS===============
	CCSprite * leftButtonSprite = CCSprite::create("Menu/Skills/[Button] Left arrow.png");
	leftButtonSprite->setScale(_scaleFactor);
	leftButtonSprite->setTag(LEFTARROW);
	leftButtonSprite->setPosition(ccp(_screenSize.width/2 - (220*_scaleFactor),_screenSize.height/2));
	this->addChild(leftButtonSprite);

	CCSprite * rightButtonSprite = CCSprite::create("Menu/Skills/[Button] Right arrow.png");
	rightButtonSprite->setScale(_scaleFactor);
	rightButtonSprite->setTag(RIGHTARROW);
	rightButtonSprite->setPosition(ccp(_screenSize.width/2 + (220*_scaleFactor),_screenSize.height/2));
	this->addChild(rightButtonSprite);

	//================BUTTONS======================
	//Start button
	CCSprite * backButtonSprite = CCSprite::create("Menu/Skills/[Button] Back - Normal.png");
	CCSprite * backButtonSpritePressed = CCSprite::create("Menu/Skills/[Button] Back - Pressed.png");
	CCMenuItemSprite* backButton = CCMenuItemSprite::create(backButtonSprite,backButtonSpritePressed,this,menu_selector(SkillSelectScreen::backButtonPressed));
	backButton->setScale(_scaleFactor);
	backButton->setPosition(ccp((50*_scaleFactor),(50*_scaleFactor)));

	CCSprite * playButtonSprite = CCSprite::create("Menu/Skills/[Button] Play - Normal.png");
	CCSprite * playButtonSpritePressed = CCSprite::create("Menu/Skills/[Button] Play - Pressed.png");
	CCMenuItemSprite* playButton = CCMenuItemSprite::create(playButtonSprite,playButtonSpritePressed,this,menu_selector(SkillSelectScreen::playButtonPressed));
	playButton->setScale(_scaleFactor);
	playButton->setPosition(ccp(_screenSize.width/2 + (270*_scaleFactor),(70*_scaleFactor)));

    CCMenu* mainmenu = CCMenu::create(playButton, backButton, NULL);
    mainmenu->setPosition(0,0);
    mainmenu->setTag(MAINMENU);
	this->addChild(mainmenu);
}

/*!
 * @function: ccTouchesBegan
 * @brief: Cocos2d-x default library for touches began, this function is called for every touch that touch the device's screen
 */
void SkillSelectScreen::ccTouchesBegan(CCSet* touches, CCEvent* event)
{
	CCTouch* touch = (CCTouch*)(touches->anyObject());
	CCPoint location = touch->getLocationInView();
	location = CCDirector::sharedDirector()->convertToGL(location);

	//Left button
	CCSprite *leftarrow = (CCSprite*)this->getChildByTag(LEFTARROW);
	CCSprite *rightarrow = (CCSprite*)this->getChildByTag(RIGHTARROW);

	if( leftarrow->boundingBox().containsPoint(location) )
	{
		if( _currentPanel == 0 )
			return;

		_currentPanel--;
		if( _currentPanel == 0 )
		{
			leftarrow->setTexture(CCTextureCache::sharedTextureCache()->addImage("Menu/Skills/[Button] Left arrow.png"));
			leftarrow->setFlipX(false);
		}
		else if( _currentPanel == MAXSKILLS-2 )
		{
			rightarrow->setTexture(leftarrow->getTexture());
			rightarrow->setFlipX(false);
		}

		CCSize _screenSize = CCDirector::sharedDirector()->getWinSize();
		for( int i = 0 ; i < MAXSKILLS ; i++ )
		{
			CCSprite *panel = (CCSprite*)this->getChildByTag(SKILLPANEL+i);
			panel->runAction(CCMoveBy::create(0.5,ccp(_screenSize.width/2,0)));
		}

		return;
	}
	//Right button
	else if( rightarrow->boundingBox().containsPoint(location) )
	{
		if( _currentPanel == (MAXSKILLS-1) )
			return;

		CCSize _screenSize = CCDirector::sharedDirector()->getWinSize();

		_currentPanel++;
		if( _currentPanel == 1 )
		{
			leftarrow->setTexture(rightarrow->getTexture());
			leftarrow->setFlipX(true);
		}
		else if( _currentPanel == MAXSKILLS-1 )
		{
			rightarrow->setTexture(CCTextureCache::sharedTextureCache()->addImage("Menu/Skills/[Button] Left arrow.png"));
			rightarrow->setFlipX(true);
		}


		for( int i = 0 ; i < MAXSKILLS ; i++ )
		{
			CCSprite *panel = (CCSprite*)this->getChildByTag(SKILLPANEL+i);
			panel->runAction(CCMoveBy::create(0.5,ccp(-_screenSize.width/2,0)));
		}

		return;
	}

	//3 base click
	for( int i = 0 ; i < 3 ; i++ )
	{
		CCSprite *slot = (CCSprite*)this->getChildByTag(SKILLSLOT+i);
		if( slot->boundingBox().containsPoint(location) && i != _currentSelectedSlot )
		{
			//Remove old base frame
			CCSprite *currentslot = (CCSprite*)this->getChildByTag(SKILLSLOT+_currentSelectedSlot);
			currentslot->setDisplayFrame(CCSpriteFrame::create("Menu/Skills/[Skill Button] Base.png",CCRectMake(0,0,134,129)));

			//Update to selected base frame
			_currentSelectedSlot = i;
			slot->setDisplayFrame(CCSpriteFrame::create("Menu/Skills/[Skill Button] Base Selected.png",CCRectMake(0,0,134,129)));
		}
	}

	//Skill button, check if skill is not already selected
	CCSprite *skillImage = (CCSprite*)(this->getChildByTag(SKILLPANEL+_currentPanel)->getChildByTag(SKILLPANELSKILLIMAGE+_currentPanel));
	if( skillImage->boundingBox().containsPoint(skillImage->convertTouchToNodeSpace(touch)+ccp(skillImage->boundingBox().size.width,skillImage->boundingBox().size.height))
		&& _slots[_currentSelectedSlot] != _currentPanel )
	{
		//Check if there exist a skill image, else replace it
		//Empty skill base
		if( _slots[_currentSelectedSlot] == -1 )
		{
			//Get base location
			CCSprite *baseslotimage = (CCSprite*)this->getChildByTag(SKILLSLOT+_currentSelectedSlot);

			CCSprite *insertimage = CCSprite::createWithTexture(skillImage->getTexture());
			insertimage->setTag(SKILLSLOTIMAGE+_currentSelectedSlot);
			insertimage->setPosition(baseslotimage->getPosition()+ccp(2*_scaleFactor,-1*_scaleFactor));
			insertimage->setScale(_scaleFactor-(0.6*_scaleFactor));

			this->addChild(insertimage);
		}
		//Already has existing skill, hence we have to remove old image and replace it with new one
		else
		{
			CCSprite *removeimage  = (CCSprite*)this->getChildByTag((SKILLSLOTIMAGE+_currentSelectedSlot));
			removeimage->setTexture(skillImage->getTexture());
		}

		//Update skill with selected skill
		_slots[_currentSelectedSlot] = _currentPanel;

		//Remove old base frame
		CCSprite *currentslot = (CCSprite*)this->getChildByTag(SKILLSLOT+_currentSelectedSlot);
		currentslot->setDisplayFrame(CCSpriteFrame::create("Menu/Skills/[Skill Button] Base.png",CCRectMake(0,0,134,129)));
		//Switch to next frame
		_currentSelectedSlot = (_currentSelectedSlot+1)%3;
		CCSprite *newslot = (CCSprite*)this->getChildByTag(SKILLSLOT+_currentSelectedSlot);
		newslot->setDisplayFrame(CCSpriteFrame::create("Menu/Skills/[Skill Button] Base Selected.png",CCRectMake(0,0,134,129)));
	}
}

/*
 * @function: returnToPreviousScreen
 * @brief: function to return back to main menu screen when back button is pressed
 * @result: return to main menu screen
 */
void SkillSelectScreen::returnToPreviousScreen()
{
	//Remove additional panels so it won't be seen during transition
	for( int i = 0 ; i < MAXSKILLS ; i++ )
	{
		if( i != _currentPanel )
			this->removeChildByTag(SKILLPANEL+i);
	}

	_myFlowController->switchScreenTo(SCREEN_LEVELSELECT);
}

/*
 * @function: keyBackClicked
 * @brief: hardware back button function
 * @result: return to main menu screen
 */
void SkillSelectScreen::keyBackClicked()
{
	returnToPreviousScreen();
}

/*
 * @function: backButtonPressed
 * @brief: UI back button pressed
 * @result: return to main menu screen
 */
void SkillSelectScreen::backButtonPressed()
{
	returnToPreviousScreen();
}
/*
 * @function: playButtonPressed
 * @brief: Proceed to GameManager scene, skill data are also saved
 */
void SkillSelectScreen::playButtonPressed()
{
	//Save user preference first
	PlayerData::saveSkillNumber(1, _slots[0]);
	PlayerData::saveSkillNumber(2, _slots[1]);
	PlayerData::saveSkillNumber(3, _slots[2]);

	//Remove additional panels so it won't be seen during transition
	for( int i = 0 ; i < MAXSKILLS ; i++ )
	{
		if( i != _currentPanel )
			this->removeChildByTag(SKILLPANEL+i);
	}

	//Go to game
	_myFlowController->switchScreenTo(SCREEN_GAMESCENE);
}
